////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//  LBPoker
//
//  Created by Alexander Rinas on 4/18/12.
//  Copyright (c) 2012 Playsoft. All rights reserved.
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#import "AvatarCollection.h"
#import "GDataDefines.h"

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

@interface AvatarCollection ()

@property (nonatomic, copy) NSArray *avatars;

@end

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

@implementation AvatarCollection

@synthesize avatars = _avatars;


- (id)init
{
    return [self initWithAvatarCollectionFilename:nil];
}

- (id)initWithAvatarCollectionFilename:(NSString *)aCollectionFilename
{
    self = [super init];
    if (nil != self)
    {
        NSData *avatarsXMLData = [NSData dataWithContentsOfFile:aCollectionFilename];
        
        GDataXMLDocument *avatarsDocument = [[[GDataXMLDocument alloc] initWithData:avatarsXMLData options:0
        	error:NULL] autorelease];
     
        
        GDataXMLElement *rootElement = [avatarsDocument rootElement];

        
        NSArray *avatarElements = [rootElement elementsForName:@"Avatar"];
        NSUInteger avatarCount = [avatarElements count];
      
        
        NSMutableArray *avatars = [NSMutableArray arrayWithCapacity:avatarCount];
        for (NSUInteger avatarIndex = 0; avatarIndex < avatarCount; ++avatarIndex)
        {
            GDataXMLElement *avatarElement = [avatarElements objectAtIndex:avatarIndex];
            NSString *avatarImageName = [avatarElement stringValue];
            Avatar *avatar = [[[Avatar alloc] initWithCode:avatarIndex
            	name:[avatarImageName stringByDeletingPathExtension] imageName:avatarImageName] autorelease];
            [avatars addObject:avatar];
        }
        
        self.avatars = avatars;
    }
    
    return self;
}

- (void)dealloc
{
    self.avatars = nil;
    [super dealloc];
}

- (Avatar *)avatarWithCode:(AvatarCode)anAvatarCode
{
    return [self.avatars objectAtIndex:anAvatarCode];
}

- (Avatar *)randomAvatar
{
    return [self.avatars objectAtIndex:(random() % [self.avatars count])];
}

@end

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
